package com.ktg.mes.wm.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.ktg.common.core.domain.APIResult;
import com.ktg.mes.md.domain.MdProductBom;
import com.ktg.mes.md.service.IMdProductBomService;
import com.ktg.mes.util.LGLeftJoinQueryWrapper;
import com.ktg.mes.wm.domain.WmAssembleRecptLine;
import com.ktg.mes.wm.domain.WmItemRecptLine;
import com.ktg.mes.wm.domain.WmItemSplitLine;
import com.ktg.mes.wm.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.mes.wm.domain.WmItemSplit;
import com.ktg.common.utils.poi.ExcelUtil;

/**
 * 物料拆分Controller
 *
 * @author byteco
 * @date 2023-01-06
 */
@RestController
@RequestMapping("/wm/wmItemSplit")
public class WmItemSplitController extends BaseController
{
    @Autowired
    private IWmItemSplitService wmItemSplitService;

    @Autowired
    private IWmItemSplitLineService wmItemSplitLineService;

    @Autowired
    private IWmItemRecptLineService iWmItemRecptLineService;

    @Autowired
    private IWmStockOutService wmStockOutService;

    @Autowired
    private IWmAssembleRecptLineService assembleRecptLineService;

    @Autowired
    private IMdProductBomService mdProductBomService;



    /**
     * 查询物料拆分列表
     */
    @PreAuthorize("@ss.hasPermi('wm:wmItemSplit:list')")
    @GetMapping("/list")
    public Result<IPage<WmItemSplit>> list(WmItemSplit wmItemSplit,
                                           @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                           @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                           HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询物料拆分列表",req,null);
        try {
            LGLeftJoinQueryWrapper lgLeftJoinQueryWrapper = new LGLeftJoinQueryWrapper<>(wmItemSplit,req.getParameterMap(),pageNo,pageSize);
            lgLeftJoinQueryWrapper.orderByDesc("create_time");
            IPage pageList = wmStockOutService.lgPageMapList(lgLeftJoinQueryWrapper);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 导出物料拆分列表
     */
    @PreAuthorize("@ss.hasPermi('wm:wmItemSplit:export')")
    @Log(title = "物料拆分", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmItemSplit wmItemSplit, HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出物料拆分列表",req, wmItemSplit);
        try {
            List<WmItemSplit> list = wmItemSplitService.queryList(wmItemSplit);
            ExcelUtil<WmItemSplit> util = new ExcelUtil<WmItemSplit>(WmItemSplit.class);
            util.exportExcel(response, list, "物料拆分数据");
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }

    /**
     * 获取物料拆分详细信息
     */
    @PreAuthorize("@ss.hasPermi('wm:wmItemSplit:query')")
    @GetMapping(value = "/{lineId}")
    public Result<WmItemSplit> getInfo(@PathVariable("lineId") Long lineId, HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取物料拆分详细信息",req,null);
        try {
            WmItemSplit wmItemSplit = new WmItemSplit();
            wmItemSplit.setLineId(lineId);
            LGLeftJoinQueryWrapper lgLeftJoinQueryWrapper = new LGLeftJoinQueryWrapper<>(wmItemSplit,req.getParameterMap());
            JSONObject object = wmStockOutService.lgOneMap(lgLeftJoinQueryWrapper);
            return apiLog.ok(object);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 新增物料拆分
     */
    @PreAuthorize("@ss.hasPermi('wm:wmItemSplit:add')")
    @Log(title = "物料拆分", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public Result<String> add(@RequestBody WmItemSplit wmItemSplit, HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增物料拆分",req, wmItemSplit);
        try {

            //修改总库存量
            wmItemSplitService.insert(wmItemSplit);

            MdProductBom mdProductBom = new MdProductBom();
            mdProductBom.setItemId(wmItemSplit.getItemId());
            mdProductBom.setEnableFlag("Y");
            List<MdProductBom> bomList = mdProductBomService.selectMdProductBomList(mdProductBom);
            Map map1 = new HashMap<>();
            Map map2 = new HashMap<>();
            float allCount = 0;
            if (bomList != null && bomList.size() > 0){
                for (int i = 0; i < bomList.size(); i++) {
                    allCount += bomList.get(i).getQuantity().floatValue();
                    map1.put(bomList.get(i).getBomItemName(),Float.valueOf(bomList.get(i).getQuantity().floatValue()));
                    map2.put(bomList.get(i).getBomItemName(),Float.valueOf(0));
                }
            }

            WmAssembleRecptLine wmAssembleRecptLine = new WmAssembleRecptLine();
            wmAssembleRecptLine.setItemRecptLineId(wmItemSplit.getFromItemRecptLineId());
            LGLeftJoinQueryWrapper<WmAssembleRecptLine> wmAssembleRecptLineLGLeftJoinQueryWrapper = new LGLeftJoinQueryWrapper<>(wmAssembleRecptLine,null);
            List<JSONObject> jsonObjectList = wmStockOutService.lgListMap(wmAssembleRecptLineLGLeftJoinQueryWrapper);

            if (jsonObjectList != null && jsonObjectList.size() > 0){
                for (int i = 0; i < jsonObjectList.size(); i++) {
                    JSONObject item = jsonObjectList.get(i);
                    String name = item.getString("itemName");
                    Long fromItemRecptLineId = item.getLongValue("fromItemRecptLineId");
                    Long recordId = item.getLongValue("recordId");
                    float quantityRecived = item.getFloatValue("quantityRecived");
                    float usCount = ((Float) map2.get(name)).floatValue();

                    WmItemRecptLine wmItemRecptLine = iWmItemRecptLineService.getById(fromItemRecptLineId);

                    WmItemSplitLine newItem = new WmItemSplitLine();
                    newItem.setItemSplitLineId(wmItemSplit.getLineId());
                    newItem.setFromItemRecptLineId(fromItemRecptLineId);
                    newItem.setFromAssembleRecptLineId(recordId);
                    newItem.setItemId(item.getLong("itemId"));
                    newItem.setWarehouseId(wmItemSplit.getWarehouseId());
                    newItem.setMeterialCode(wmItemRecptLine.getMeterialCode());
                    newItem.setBatchCode(wmItemRecptLine.getBatchCode());

                    if (map1.get(name) != null){
                        float value = (float) map1.get(name);
                        float aaa = wmItemSplit.getQuantity().floatValue() * value/allCount;
                        aaa = aaa - usCount;

                        if (aaa <= quantityRecived){
                            map2.put(name,Float.valueOf(aaa));
                            newItem.setQuantityRecived(BigDecimal.valueOf(aaa));
                        }else {
                            map2.put(name,Float.valueOf(quantityRecived+usCount));
                            newItem.setQuantityRecived(BigDecimal.valueOf(quantityRecived));
                        }
                        wmItemSplitLineService.save(newItem);
                    }
                }
            }

            return apiLog.ok(wmItemSplit);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 修改物料拆分
     */
    @PreAuthorize("@ss.hasPermi('wm:wmItemSplit:edit')")
    @Log(title = "物料拆分", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public Result<String> edit(@RequestBody WmItemSplit wmItemSplit, HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改物料拆分",req, wmItemSplit);
        try {
            wmItemSplitService.update(wmItemSplit);
            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 删除物料拆分
     */
    @PreAuthorize("@ss.hasPermi('wm:wmItemSplit:remove')")
    @Log(title = "物料拆分", businessType = BusinessType.DELETE)
	@DeleteMapping("/{lineIds}")
    public Result<String> remove(@PathVariable Long[] lineIds,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("删除物料拆分",req,null);
        try {
            wmItemSplitService.delete(lineIds);
            return apiLog.ok("删除成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }

    }
}
